﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;
using System.Xml;
using WebServer.Biz;
using WebServer.Models;

namespace WebServer
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码、svc 和配置文件中的类名“SendCode”。
    // 注意: 为了启动 WCF 测试客户端以测试此服务，请在解决方案资源管理器中选择 SendCode.svc 或 SendCode.svc.cs，然后开始调试。
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class SendCode : ISendCode
    { 
        #region 邮箱验证码
        /// <summary>
        /// 邮件发送 0-注册验证；1找回密码
        /// </summary>
        /// <param name="Email"></param>
        /// <param name="Title"></param>
        /// <param name="Body"></param>
        /// <param name="mod"></param>
        /// <returns></returns>
        public MsgEntity SendEmail(string Email, int Type, string returnUrl)
        {
            MsgEntity request = new MsgEntity();
            int hasUser = new UserBiz().HasUser(Email, 0);
            if (hasUser > 0 && Type == 4) {

                request.Code = 30001;
                request.Msg = "此邮箱已经被使用，如有疑问请联系客服";
                return request;
            
            }




           
            try
            {
                string Title = "";
                string Body = "";
                string GuID = System.Guid.NewGuid().ToString();
                string mycode = new SendCodeBiz().ValidateCode(6);

                if (Type == 0)
                {
                    
                    string Url = returnUrl + "?Email=" + Email + "&Code=" + GuID;
                    Title = "绑定邮箱 - 17YBK.COM欢迎您的加入";
                    Body = new SendCodeBiz().RegHtml(Url);
                }
                else if (Type == 1)
                {
                    Title = "找回密码 - 17YBK.COM欢迎您回来";
                    Body = new SendCodeBiz().PassHtml(mycode);

                }
                else if (Type == 2)
                {
                    Title = "尊敬的用户";
                    Body = new SendCodeBiz().CheckHtml(returnUrl,Type);
                }
                else if (Type == 3)
                {
                    Title = "尊敬的用户";
                    Body = new SendCodeBiz().CheckHtml(returnUrl,Type);
                }
                else if (Type == 4)
                {
                    Title = "绑定邮箱 - 一起邮币卡一路伴随您";
                    Body = new SendCodeBiz().BoundHtml(mycode);

                }
                else { 
                
                }

                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                msg.To.Add(Email);

                // uyxwqfdllkirtsoz
                /* 
                * msg.CC.Add("c@c.com"); 
                * msg.CC.Add("c@c.com");可以抄送给多人 
                */
                msg.From = new MailAddress("15000147424@163.com", "17YBK.COM", System.Text.Encoding.UTF8);
                /* 上面3个参数分别是发件人地址（可以随便写），发件人姓名，编码*/
                msg.Subject = Title;//邮件标题 
                msg.SubjectEncoding = System.Text.Encoding.UTF8;//邮件标题编码 
                msg.Body = Body;//邮件内容 
                msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码 
                msg.IsBodyHtml = true;//是否是HTML邮件 
                msg.Priority = MailPriority.High;//邮件优先级 
                SmtpClient client = new SmtpClient();
                client.Credentials = new System.Net.NetworkCredential("15000147424@163.com", "uyxwqfdllkirtsoz");
                //上述写你的GMail邮箱和密码  
                client.Host = "smtp.163.com";
                client.EnableSsl = true;//经过ssl加密 
                object userState = msg;
                try
                {
                    //client.SendAsync(msg, userState);
                    ////简单一点儿可以
                    client.Send(msg);
                    if (Type == 0)
                    {
                        new SendCodeBiz().Insert(Email, "", GuID, DateTime.Now.AddHours(2), true);
                    }
                    else if (Type == 1)
                    {
                        new SendCodeBiz().Insert(Email, "", mycode, DateTime.Now.AddMinutes(5), true);
                    }
                    else if (Type == 2)
                    {
                        //new SendCodeBiz().Insert(Email, "", mycode, DateTime.Now.AddMinutes(5), true);
                    }
                    else if (Type == 4)
                    {
                        new SendCodeBiz().Insert(Email, "", mycode, DateTime.Now.AddMinutes(20), true);

                    }
                    else
                    {

                    }
                   
                    request.Code = 10000;
                    request.Msg = "成功";
                    return request;
                }
                catch (System.Net.Mail.SmtpException ex)
                {
                    request.Code = 20000;
                    request.Msg = ex.ToString();
                    return request;
                }
            }
            catch (Exception ex)
            {
                request.Code = 20001;
                request.Msg = ex.ToString();
                return request;
            }
        }



        #endregion

        #region 测试
        /// <summary>
        /// 邮件发送 0-注册验证；1找回密码
        /// </summary>
        /// <param name="Email"></param>
        /// <param name="Title"></param>
        /// <param name="Body"></param>
        /// <param name="mod"></param>
        /// <returns></returns>
        public MsgEntity TestSendEmail(string FromEmail,string PassWord,string Email,string Code)
        {
            MsgEntity request = new MsgEntity();
          
            try
            {
                string Title = "";
                string Body = "";
                //string GuID = System.Guid.NewGuid().ToString();
                //string mycode = new SendCodeBiz().ValidateCode(6);

                Title = "尊敬的" + Code + "号经济会员，您好";
                Body = new SendCodeBiz().TestCheckHtml(Code);

                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                msg.To.Add(Email);

                // uyxwqfdllkirtsoz
                /* 
                * msg.CC.Add("c@c.com"); 
                * msg.CC.Add("c@c.com");可以抄送给多人 
                */
                msg.From = new MailAddress(FromEmail, "17YBK.COM", System.Text.Encoding.UTF8);
                /* 上面3个参数分别是发件人地址（可以随便写），发件人姓名，编码*/
                msg.Subject = Title;//邮件标题 
                msg.SubjectEncoding = System.Text.Encoding.UTF8;//邮件标题编码 
                msg.Body = Body;//邮件内容 
                msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码 
                msg.IsBodyHtml = true;//是否是HTML邮件 
                msg.Priority = MailPriority.High;//邮件优先级 
                SmtpClient client = new SmtpClient();
                //client.Credentials = new System.Net.NetworkCredential("15000147424@163.com", "uyxwqfdllkirtsoz");
                client.Credentials = new System.Net.NetworkCredential(FromEmail, PassWord);
                //上述写你的GMail邮箱和密码  
                client.Host = "smtp.163.com";
                //client.Host = "smtp.exmail.qq.com";
                client.EnableSsl = true;//经过ssl加密 
                object userState = msg;
                try
                {
                    //client.SendAsync(msg, userState);
                    ////简单一点儿可以
                    client.Send(msg);
               
                    request.Code = 10000;
                    request.Msg = "成功";
                    return request;
                }
                catch (System.Net.Mail.SmtpException ex)
                {
                    request.Code = 20000;
                    request.Msg = ex.ToString();
                    return request;
                }
            }
            catch (Exception ex)
            {
                request.Code = 20001;
                request.Msg = ex.ToString();
                return request;
            }
        }



        #endregion

        #region 手机验证码
        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <param name="url">请求的URL</param>
        /// <param name="param">请求的参数</param>
        /// <returns>请求结果</returns>
        public MsgEntity SendMobileCode(string Mobile)
        {
            MsgEntity back = new MsgEntity();

            int hasUser = new UserBiz().HasUser(Mobile, 1);
            if (hasUser > 0)
            {

                back.Code = 30001;
                back.Msg = "此手机已经被使用，如有疑问请联系客服";
                return back;

            }

            //先判断数据库是否存在可用状态
            string U = new SendCodeBiz().HasCode(Mobile);
            //bool U = new SendCodeBiz().HasCode(Mobile);
            if (U == "")
            {
                string sendCode = new SendCodeBiz().ValidateCode(6);
                Dictionary<string, object> Response = new Dictionary<string, object>();
                string url = "http://apis.baidu.com/kingtto_media/106sms/106sms";

                string cont = "【一起邮币卡】您的此次验证码：" + sendCode + "(验证码20分钟内有效，请在时间内完成验证！)";


                string param = "mobile=" + Mobile + "&content=" + cont;
                string ResponseHtml = string.Empty;
                string strURL = url + '?' + param;
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                request.Method = "GET";
                // 添加header
                request.Headers.Add("apikey", "dbcae506977c1990a19011ef8d5e9d14");
                System.Net.HttpWebResponse response;
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream s;
                s = response.GetResponseStream();
                StreamReader Reader = new StreamReader(s, Encoding.UTF8);
                ResponseHtml = Reader.ReadToEnd(); //读完流
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(ResponseHtml);
                XmlNodeList xmlNodeList = xDoc.SelectNodes("/returnsms");
                string message = (xmlNodeList[0].SelectSingleNode("//message")).InnerText;   //这边就可以获得节点的值了

                //Response = new SendCodeBiz().JsonToDictionary(ResponseHtml);
                //int bcode = (int)Response["result"];
                if (message == "ok")
                {
                    string oK = new SendCodeBiz().Insert("", Mobile, sendCode, DateTime.Now.AddMinutes(20), true);
                    back.Code = 10000;
                    back.Msg = sendCode;
                    
                }
                else
                {
                    back.Code = 20000;
                    back.Msg = "失败";
                }
            }
            else
            {
                back.Code = 10000;
                back.Msg = U;
            }
            return back;
        }

        /// <summary>
        /// 发送手机通知通过审核
        /// </summary>
        /// <param name="url">请求的URL</param>
        /// <param name="param">请求的参数</param>
        /// <returns>请求结果</returns>
        public MsgEntity SendMobileInform(string Mobile, string CateName, bool IsOpen)
        {
            MsgEntity back = new MsgEntity();
            //先判断数据库是否存在可用状态
            //bool U = new SendCodeBiz().HasCode(Mobile);
            //if (U == false)
            //{
                //string sendCode = new SendCodeBiz().ValidateCode(6);
                Dictionary<string, object> Response = new Dictionary<string, object>();
                string url = "http://apis.baidu.com/kingtto_media/106sms/106sms";
                string cont = "";
                if (IsOpen == true)
                {
                    cont = "【17YBK】尊敬的用户：审核通过，恭喜您成为" + CateName + "";
                }
                else
                {
                    cont = "【17YBK】尊敬的用户：您申请成为" + CateName + "审核未通过。详情请查看私信";
                }


                string param = "mobile=" + Mobile + "&content=" + cont;
                string ResponseHtml = string.Empty;
                string strURL = url + '?' + param;
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                request.Method = "GET";
                // 添加header
                request.Headers.Add("apikey", "dbcae506977c1990a19011ef8d5e9d14");
                System.Net.HttpWebResponse response;
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream s;
                s = response.GetResponseStream();
                StreamReader Reader = new StreamReader(s, Encoding.UTF8);
                ResponseHtml = Reader.ReadToEnd(); //读完流
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(ResponseHtml);
                XmlNodeList xmlNodeList = xDoc.SelectNodes("/returnsms");
                string message = (xmlNodeList[0].SelectSingleNode("//message")).InnerText;   //这边就可以获得节点的值了

                //Response = new SendCodeBiz().JsonToDictionary(ResponseHtml);
                //int bcode = (int)Response["result"];
                if (message == "ok")
                {
                    //string oK = new SendCodeBiz().Insert("", Mobile, sendCode, DateTime.Now.AddMinutes(20), true);
                    back.Code = 10000;
                    back.Msg = "成功";

                }
                else
                {
                    back.Code = 20000;
                    back.Msg = "失败";
                }
            //}
            //else
            //{
            //    back.Code = 10000;
            //    back.Msg = "存在有效验证码";
            //}
            return back;
        }

        #endregion

        #region 验证



        /// <summary>
        /// 认证
        /// </summary>
        /// <param name="Email"></param>
        /// <param name="Mobile"></param>
        /// <param name="Code"></param>
        /// <returns></returns>
        public bool LoginCode(string Email, string Mobile, string Code)
        {

            bool request = false;
            request = new SendCodeBiz().LoginCode(Email, Mobile, Code);
            return request;
        }

        /// <summary>
        /// 认证
        /// </summary>
        /// <param name="Email"></param>
        /// <param name="Mobile"></param>
        /// <param name="Code"></param>
        /// <returns></returns>
        public bool SecurityLogin(string Email, string Mobile, string Code)
        {
            bool request = false;
            request = new SendCodeBiz().SecurityLogin(Email, Mobile, Code);
            return request;
        }
        #endregion


    }
}
